<template>
  <div class="page">
    <div class="head">
      <h1>{{ $t('真假美猴王') }}</h1>
      <router-link class="record-icon" tag="div" to="/fightrecords"></router-link>
    </div>
    <div class="panel">
      <div class="monkey">
        <h4>选择大圣：</h4>
        <div class="item">
          <div class="img real" @click="showList('选择大圣', 1)">
            <img v-if="monkeyKing" :src="monkeyKing.facade" :style="{background: monkeyKing.background}">
          </div>
          <div v-if="monkeyKing">
            <p># {{monkeyKing.id}} · {{monkeyKing.generation}} 代 · {{monkeyKing.weight}}kg</p>
            <p>
              <span>成长：{{monkeyKing.grow}}</span>
              <span>生育：{{monkeyKing.bear}}</span>
              <span>力量：{{monkeyKing.makeMoney}}</span>
            </p>
          </div>
        </div>
      </div>
      <div class="dash"></div>
      <div class="monkey">
        <h4>选择猕猴：</h4>
        <div class="item">
          <div class="img fake" @click="showList('选择猕猴', 2)">
            <img v-if="fakeMonkeyKing" :src="fakeMonkeyKing.facade" :style="{background: fakeMonkeyKing.background}">
          </div>
          <div v-if="fakeMonkeyKing">
            <p># {{fakeMonkeyKing.id}} · {{fakeMonkeyKing.generation}} 代 · {{fakeMonkeyKing.weight}}kg</p>
            <p>
              <span>成长：{{fakeMonkeyKing.grow}}</span>
              <span>生育：{{fakeMonkeyKing.bear}}</span>
              <span>力量：{{fakeMonkeyKing.makeMoney}}</span>
            </p>
          </div>
        </div>
        <div class="checker" v-if="forceFightNum">
          <check-icon :value.sync="forceFight">使用战书({{ forceFightNum }})</check-icon>
        </div>
      </div>
    </div>
    <div class="panel" v-if="this.monkeyKing && this.fakeMonkeyKing">
      <h4 class="title">获胜预览（仅供预览，以实际结果为准）</h4>
      <div class="result">
        <img v-if="monkeyKing" :src="monkeyKing.facade" :style="{background: monkeyKing.background}">
        <div class="info">
          <p>成长：{{monkeyKing.grow}}<span>+{{loseProp(monkeyKing.grow,fakeMonkeyKing.grow) | toFix(5)}}</span></p>
          <p>生育：{{monkeyKing.bear}}<span>+{{loseProp(monkeyKing.bear,fakeMonkeyKing.bear) | toFix(5)}}</span></p>
          <p>力量：{{monkeyKing.makeMoney}}<span>+{{loseProp(monkeyKing.makeMoney,fakeMonkeyKing.makeMoney) | toFix(5)}}</span></p>
          <p>体重：{{monkeyKing.weight}}kg<span>+{{loseWeight(monkeyKing.weight,fakeMonkeyKing.weight) | toFix(5)}}kg</span></p>
        </div>
      </div>
    </div>
    <div class="panel" v-if="this.monkeyKing && this.fakeMonkeyKing">
      <box gap="20px 0">
        <x-button class="btn" plain @click.native="fightConfirm()">
          <p>Fight !</p>
          <span v-if="monkeyKing">消耗 {{ monkeyKing.monkeyToken }} 猴毛</span>
        </x-button>
      </box>
    </div>
    <div class="panel">
      <h3 class="help" @click="showRules = !showRules">玩法说明</h3>
      <div class="rules" :class="{'rules-show': showRules}">
        <h4>玩法介绍：</h4>
        <p>每天每只小猴可以以“大圣”的身份参与一次“真假美猴王”活动，每次活动需要选取一只当天投食满5颗桃子的“猕猴”，大圣花费猴毛开始战斗，战斗结束后，大圣有几率获得猕猴的部分属性值与体重，猕猴会被送入“佛祖的钵盂”，等待有缘人的解救。</p>
        <h4>玩法规则：</h4>
        <p>
          参与战斗的大圣与猕猴必须为空闲状态，集市与生育状态都不能参与。
          <br><br>只有当天投食满5颗桃子的小猴才能被当做“猕猴”，战斗失败的猕猴当天可以再次参与美猴王活动。
          <br><br>大圣的每次战斗，无论战斗成功与失败都需要花费猴毛，具体为0代1200，1代1000，2代800，3代600，4代400，5代200，6代及6代以后100。每只小猴每天只能以“大圣”角色参与一次活动。
          <br><br>大圣与猕猴的战斗失败概率为50%，失败后猕猴状态不变，猕猴可以再选择另一只大圣继续战斗；有40%概率“胜利”，成功后大圣将会夺取猕猴全部属性的10%与体重的20%；有10%概率触发“大获全胜”，大圣将会夺取猕猴全部属性的20%与体重的40%，夺取的属性对应增加至大圣各项属性。
          <br><br>大圣战胜猕猴，猕猴将会重置属性与投食记录后送入“佛祖的钵盂”，玩家永久失去“猕猴”，即划入系统账号“佛祖的钵盂”。猕猴将在后续的玩法另做他用，猕猴当天的投食金额将会进入掘金池，且该猕猴在重新启用之前不再产生掘金与猴毛收益。
          <br><br>大圣夺取的体重将受到体重衰减规则制约，将按体重衰减规则计算最终获得的体重值。
          <br><br>大圣夺取的属性将受到属性上限的约束，属性不能超出5，大圣夺取的属性为猕猴属性对应值，若大圣拥有生育属性而猕猴没有生育属性，则生育属性不获得提升。
          <br><br>猴毛花费数额与成功概率，可能会根据系统实际情况进行微调，官方团队保留调整之权利。
        </p>
      </div>
    </div>
    <div v-transfer-dom>
      <popup v-model="showPicker" height="80%" class="picker-list">
        <h2>{{ pickerTitle }}</h2>
        <div class="filter">
          <ul class="order">
            <li :class="{'active': item.value == params.orderBy,'up': params.sort == 0}" @click="changeOrder(item.value)" v-for="(item, index) in order" :key="index">{{$t(item.name)}}</li>
          </ul>
          <div class="btns">
            <div class="option" @click="showFilter = true"></div>
          </div>
        </div>
        <div class="panel" @click="chooseMonkey(item)" v-if="(!item.fighting || monkeyType == 2) && ( monkeyType == 1 || item.generation > 3)" v-for="(item,index) in records" :key="index">
          <div class="img">
            <img :src="item.facade" :style="{background: item.background}">
          </div>
          <ul class="info">
            <li>
              <div>
                <span>ID：</span>
                <em># {{ item.id }}</em>
              </div>
              <div>
                <span>成长：</span>
                <em>{{ item.grow }}</em>
              </div>
            </li>
            <li>
              <div>
                <span>代数：</span>
                <em>{{ item.generation }}</em>
              </div>
              <div>
                <span>力量：</span>
                <em>{{ item.makeMoney }}</em>
              </div>
            </li>
            <li>
              <div>
                <span>体重：</span>
                <em>{{ item.weight }}kg</em>
              </div>
              <div>
                <span>生育：</span>
                <em>{{ item.bear }}</em>
              </div>
            </li>
          </ul>
        </div>
        <infinite-loading @infinite="getMyMonkeys" ref="infiniteLoading">
          <span slot="no-more"></span>
          <div slot="no-results">
            <br>
            <empty></empty>
          </div>
          <spinner slot="spinner" type="lines"></spinner>
        </infinite-loading>
      </popup>
    </div>
    <!-- 复杂筛选 -->
    <div v-transfer-dom>
      <popup v-model="showFilter" position="right" width="100%" class="filters">
        <div class="wrap">
          <div class="block">
            <group :title="$t('代数')" class="input-range">
              <x-input v-model="params.startGen" type="number" novalidate :placeholder="$t('最低')"></x-input>
              <div class="dash"></div>
              <x-input v-model="params.endGen" type="number" novalidate :placeholder="$t('最高')"></x-input>
            </group>
            <group :title="$t('体重')" class="input-range">
              <x-input v-model="params.startWeight" type="number" novalidate :placeholder="$t('最低')"></x-input>
              <div class="dash"></div>
              <x-input v-model="params.endWeight" type="number" novalidate :placeholder="$t('最高')"></x-input>
            </group>
            <group :title="$t('力量值')" class="input-range">
              <x-input v-model="params.startMakeMoney" type="number" novalidate :placeholder="$t('最低')"></x-input>
              <div class="dash"></div>
              <x-input v-model="params.endMakeMoney" type="number" novalidate :placeholder="$t('最高')"></x-input>
            </group>
            <group :title="$t('ID')" class="input-range full">
              <x-input v-model="params.id" type="number" novalidate :placeholder="$t('输入ID')"></x-input>
            </group>
          </div>
        </div>
        <div class="button">
          <x-button type="warn" class="btn" @click.native="resetFilter">{{$t('重置')}}</x-button>
          <x-button type="primary" class="btn" @click.native="enterFilter">{{$t('确定')}}</x-button>
        </div>
      </popup>
    </div>
  </div>
</template>

<script>
  import {
    XButton,
    Box,
    TransferDomDirective as TransferDom,
    Popup,
    XDialog,
    Spinner,
    CheckIcon,
    Group,
    XInput
  } from 'vux'
  import empty from './common/empty.vue'
  import InfiniteLoading from 'vue-infinite-loading';
  export default {
    directives: {
      TransferDom
    },
    components: {
      XButton,
      Box,
      Popup,
      XDialog,
      Spinner,
      empty,
      InfiniteLoading,
      CheckIcon,
      Group,
      XInput
    },
    data() {
      return {
        showPicker: false,
        records: [],
        monkeyKing: null,
        fakeMonkeyKing: null,
        monkeyType: null,
        pickerTitle: '',
        showRules: false,
        forceFight: false,
        forceFightNum: 0,
        showFilter: false,
        params: {
          current: 1,
          orderBy: 1,
          sort: 0,
          startGen: '',
          endGen: '',
          startMakeMoney: '',
          endMakeMoney: '',
          startWeight: '',
          endWeight: '',
          id: ''
        },
        order: [{
            name: 'ID',
            value: '1'
          },
          {
            name: '代数',
            value: '2'
          },
          {
            name: '体重',
            value: '3'
          },
        ],
      }
    },
    computed: {
      rate() {
        if (this.forceFight) {
          return {
            prop: 0.03,
            wei: 0.1
          }
        } else {
          return {
            prop: 0.1,
            wei: 0.2
          }
        }
      }
    },
    mounted() {
      this.$nextTick(function() {
        this.initData()
      });
    },
    methods: {
      initData() {
        this.$http
          .get(`/game/fightData`)
          .then(res => {
            if (res.code == 200) {
              this.forceFightNum = res.result;
            } else {}
          })
          .catch(function(error) {});
      },
      getMyMonkeys($state) {
        this.$http
          .post(`/game/v2/selectMonkeyPageV2`, this.params)
          .then(res => {
            if (res.code == 200) {
              if (res.result.total > 0) {
                this.records = this.records.concat(res.result.records);
                $state.loaded();
                if (res.result.current < res.result.pages) {
                  this.params.current += 1;
                } else {
                  $state.complete();
                }
              } else {
                $state.complete();
              }
            } else {}
          })
          .catch(function(error) {});
      },
      loseWeight(realWeight, fakeWeight) {
        var overflow = realWeight - 100;
        if (overflow >= 0) {
          var range = Math.floor(overflow / 50)
          var rate = 1 / Math.pow(2, range + 1)
          return fakeWeight * this.rate.wei * rate
        } else {
          return fakeWeight * this.rate.wei
        }
      },
      loseProp(realProp, fakeProp) {
        var overflow = realProp - 5;
        if (overflow >= 0) {
          var range = Math.floor(overflow / 5)
          var rate = 1 / Math.pow(2, range + 1)
          return fakeProp * this.rate.prop * rate
        } else {
          return fakeProp * this.rate.prop
        }
      },
      changeOrder(order) {
        //点击同一个
        if (order == this.params.orderBy) {
          this.params.sort = this.params.sort == 0 ? 1 : 0;
        } else {
          this.params.orderBy = order;
          this.params.sort = 1
        }
        this.resetData()
      },
      showList(title, monkeyType) {
        this.resetData()
        this.pickerTitle = title;
        this.showPicker = true
        this.monkeyType = monkeyType
      },
      chooseMonkey(monkey) {
        if (monkey.fighting && this.monkeyType == 1) {
          this.$vux.toast.text('这只小猴累了，选个别的吧~')
          return
        }
        if (this.monkeyType == 1) {
          // 大圣
          if (this.fakeMonkeyKing && this.fakeMonkeyKing.id == monkey.id) {
            this.$vux.toast.text('不能选同一只小猴噢~')
            return
          }
          this.monkeyKing = monkey
        } else if (this.monkeyType == 2) {
          // 猕猴
          if (this.monkeyKing && this.monkeyKing.id == monkey.id) {
            this.$vux.toast.text('不能选同一只小猴噢~')
            return
          }
          this.fakeMonkeyKing = monkey
        }
        // if (this.monkeyKing && this.fakeMonkeyKing) {
        //   if (this.monkeyKing.id == this.fakeMonkeyKing.id) {
        //     this.$vux.toast.text('不能选同一只小猴噢~')
        //     return
        //   }
        // }
        this.showPicker = false
      },
      resetData() {
        this.params.current = 1;
        this.records = []
        this.$refs.infiniteLoading.$emit('$InfiniteLoading:reset');
      },
      resetFilter() {
        this.params.startGen = '';
        this.params.endGen = '';
        this.params.startMakeMoney = '';
        this.params.endMakeMoney = '';
        this.params.startWeight = '';
        this.params.endWeight = '';
        this.params.id = '';
      },
      enterFilter() {
        this.$nextTick(() => {
          this.resetData()
          this.showFilter = false
        });
      },
      fightConfirm() {
        if (!this.monkeyKing || !this.fakeMonkeyKing) {
          this.$vux.toast.text('请先选择小猴噢~')
          return
        }
        var that = this;
        this.$vux.confirm.show({
          title: `提示`,
          content: `
                                  <p>确认<strong style="color: red">消耗 ${ this.monkeyKing.monkeyToken } 猴毛</strong>开始战斗吗?</p>
                                  `,
          cancelText: '取消',
          confirmText: '开始',
          onCancel() {
            that.$vux.toast.text('已取消')
          },
          onConfirm() {
            that.fight()
          }
        })
      },
      fight() {
        this.$http
          .post(`/game/fightActivity`, {
            realityMonkeyId: this.monkeyKing.id,
            fakeMonkeyId: this.fakeMonkeyKing.id,
            gauntlet: this.forceFight
          })
          .then(res => {
            if (res.code == 200) {
              switch (res.result.status) {
                case 0:
                  // 失败
                  this.failed()
                  break;
                case 1:
                  // 成功
                  this.success(res.result)
                  break;
                case 2:
                  // 暴击
                  this.success(res.result)
                  break;
              }
            } else {
              this.$vux.toast.text(res.msg)
            }
          })
          .catch(function(error) {});
      },
      failed() {
        var that = this;
        this.$vux.confirm.show({
          title: `提示`,
          content: `
                                  <p>胜败乃兵家常事，大圣请明日再战！</p>
                                  `,
          cancelText: '离开',
          confirmText: '再战！',
          onCancel() {
            that.$router.go(-1)
          },
          onConfirm() {
            that.monkeyKing = null
          }
        })
      },
      success(res) {
        var that = this;
        var info = `体重 +${res.weight},成长 +${res.grow},力量 +${res.money}`;
        var title = '恭喜！胜利了！'
        if (res.bear) {
          info += `,生育 + ${res.bear}`
        }
        if (res.status == 2) {
          title = '恭喜！大获全胜！'
        }
        this.$vux.confirm.show({
          title: title,
          content: `
                                  <p>大圣 # ${res.realityMonkeyId}获得</p>
                                  <p>${info}</p>
                                  <p>猕猴 # ${res.fakeMonkeyId}被收入佛祖钵盂…</p>
                                  `,
          cancelText: '离开',
          confirmText: '再战！',
          onCancel() {
            that.$router.go(-1)
          },
          onConfirm() {
            that.monkeyKing = null
            that.fakeMonkeyKing = null
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .dash {
    height: 1px;
    border-top: 1px solid #ccc;
    margin: 10px 0;
  }
  .head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .record-icon {
      width: 32px;
      height: 32px;
      background: url() no-repeat 50% 50%;
      background-size: 16px 16px;
    }
  }
  .filter {
    white-space: nowrap; // flex-wrap: wrap;
    font-size: 12px;
    background: #fff;
    height: 40px;
    line-height: 40px;
    padding: 0 12px;
    margin: 0 8px 12px;
    border-radius: 4px;
    box-shadow: 3px 3px 10px 0px rgba(158, 158, 158, 0.4);
    display: flex;
    justify-content: space-between;
    &::-webkit-scrollbar {
      display: none;
    }
    ul {
      display: flex;
      align-items: center;
      li {
        cursor: pointer;
      }
    }
    .btns {
      display: flex;
      align-items: center;
      .option {
        width: 28px;
        height: 28px;
        margin-left: 5px;
        background: url() no-repeat 50%;
        background-size: 16px 16px;
      }
    }
    .order {
      color: $link;
      li+li {
        margin-left: 12px;
      }
      .active:after {
        content: '';
        display: inline-block;
        vertical-align: middle;
        margin-top: -2px;
        width: 12px;
        height: 12px;
        background: url() no-repeat 50%;
        background-size: cover;
      }
      .active.up:after {
        transform: rotate(-180deg)
      }
    }
  }
  .filters {
    overflow: hidden;
    background: #fbf9fe;
    &::-webkit-scrollbar {
      display: none;
    }
    .wrap {
      padding-bottom: 60px;
      height: 100%;
      overflow-y: scroll;
      padding: 12px;
    }
    .button {
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      display: flex;
      .btn {
        width: 50%;
        height: 40px;
        margin: 0;
        border: 0;
        border-radius: 0;
        &:after {
          display: none;
        }
      }
    }
  }
  h4 {
    color: $tmdark;
  }
  .monkey {
    .item {
      text-align: center;
      .img {
        display: inline-block;
        width: 122px;
        height: 122px;
        border: 1px solid rgba(158, 158, 158, 0.3);
        border-radius: 5px;
        overflow: hidden;
        &.real {
          background: #e0faff url(http://hp.miguan.in/common/monkeyking.svg) no-repeat 50% 50%;
          background-size: 150%;
        }
        &.fake {
          background: #ffe9e0 url(http://hp.miguan.in/common/fakemonkeyking.svg) no-repeat 50% 50%;
          background-size: 150%;
        }
      }
      img {
        width: 100%;
        height: 100%;
      }
      p {
        font-size: 14px;
        color: $gray;
        span {
          margin: 0 5px;
        }
      }
    }
  }
  .result {
    display: flex;
    img {
      width: 100px;
      height: 100px;
      flex-shrink: 0;
      margin-right: 10px;
    }
    .info {
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      height: 100px;
      font-size: 14px;
      color: $gray;
      span {
        color: $red;
        margin-left: 5px;
      }
    }
  }
  .title {
    margin-bottom: 10px;
  }
  .btn {
    width: 185px;
    height: 64px;
    line-height: 1;
    border: 1px solid $red;
    p {
      font-size: 20px;
      color: $red;
    }
    span {
      font-size: 12px;
      color: $gray;
    }
  }
  .picker-list {
    // width: 100%;
    // min-height: 100%;
    background-color: #fbf9fe;
    h2 {
      text-align: center;
      font-size: 18px;
      color: $tmdark;
      padding: 10px 0;
    }
    .panel {
      display: flex;
      .img {
        width: 60px;
        height: 60px;
        margin-right: 10px;
        flex-shrink: 0;
        img {
          width: 60px;
          height: 60px;
          background-color: #e5ffde;
        }
      }
      .info {
        height: 60px; // display: flex;
        // flex-direction: column;
        // justify-content: space-around;
        font-size: 12px;
        color: $grey;
        white-space: nowrap;
        flex: 1;
        li {
          height: 20px;
          div {
            display: inline-block;
            width: 50%;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
        span {
          color: #333;
        }
        em {
          font-style: normal;
        }
      }
      &.disable {
        filter: grayscale(100%);
        background-color: #ffebeb;
      }
    }
  }
  .help {
    text-align: center;
    font-weight: 500;
    color: $tmdark;
    font-size: 22px;
  }
  .rules {
    max-height: 0;
    overflow: hidden;
    transition: all .5s;
    padding: 0 5px;
    &.rules-show {
      max-height: 800px;
    }
    h4 {
      color: $tmdark;
    }
    p {
      line-height: 1.4;
      font-size: 14px;
      color: $gray;
      margin-bottom: 20px;
      text-align: justify;
    }
  }
  .checker {
    text-align: center;
    font-size: 14px;
  }
</style>
